from flask import request, g, jsonify, current_app
from info import db, redis_store
from info.utils.common import login_required
from info.utils.response_code import RET
from info.models import House, Order
from datetime import datetime
import time
from . import order


# 添加订单
# 获取订单列表
# 接单和拒绝单
# 评价订单

@order.route('/orders', methods=['POST'])
@login_required
def save_order():
    """添加订单"""
    user_id = g.user_id

    # 获取参数
    order_data = request.get_json()
    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    house_id = order_data.get('house_id')
    start_data_str = order_data.get('start_data')
    end_data_str = order_data.get('end_data')

    # 校验参数
    if not all([house_id, start_data_str, end_data_str]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 校验日期格式
    try:
        # 将请求的时间参数字符串转换为time类型,然后转换为timestamp类型：即：time.time形式数据，然后再转为datetime
        start_data = datetime.fromtimestamp(time.mktime(time.strftime(start_data_str, '%Y-%m-%d')))
        end_data = datetime.fromtimestamp(time.mktime(time.strftime(end_data_str, '%Y-%m-%d')))
        assert start_data <= end_data
        # 计算预定的天数
        days = (end_data - start_data).days + 1
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='日期格式错误')

    # 查询房屋是否存在
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取房屋信息失败')
    if not house:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')

    # 订单总额
    amount = days * house.price

    # 保存订单的数据
    order = Order(house_id=house_id,
                  user_id=user_id,
                  begin_data=start_data,
                  end_data=end_data,
                  days=days,
                  house_price=house.price,
                  amount=amount
                  )
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存订单失败')

    return jsonify(errno=RET.OK, errmsg="OK", data={"order_id": order.id})


@order.route('/orders', methods=['GET'])
@login_required
def get_order():
    """获取订单列表"""
    user_id = g.user_id

    # 房客身份:查询预定的房东房子的订单
    # 房东身份:查询房客预定的自己的订单
    role = request.args.get('role', '')

    # 查询订单数据
    try:
        # 房东身份
        if 'landlord' == role:
            # 先看自己有哪些房子
            houses = House.query.filter(House.user_id == user_id).all()
            # 再看自己房子被预定的订单
            orders = Order.query.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()
        # 房客身份
        else:
            # 查询自己预定的订单
            orders = Order.query.filter(Order.user_id == user_id).order_by(Order.create_time.desc()).all()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询订单失败')

    # 订单对象转化为字典
    orders_dict_list = []
    if orders:
        for order in orders:
            orders_dict_list.append(order.to_dict())

    return jsonify(errno=RET.OK, errmsg="OK", data={"orders": orders_dict_list})


@order.route('/orders', methods=['PUT'])
@login_required
def accept_reject_order(order_id):
    """接单和拒绝单"""
    user_id = g.user_id

    # 获取参数
    req_data = request.get_json()
    if not req_data:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 判断行为
    action = req_data.get('action')
    if action not in ('accept', 'reject'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 通过订单号查询订单,并且要求订单是等待接单状态
    try:
        order = Order.query.filter(Order.id == order_id, Order.status == 'WAIT_ACCEPT').first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='无法获取订单')

    if action == 'accept':
        # 接单
        order.status = 'WAIT_PAYMENT'
    elif action == 'reject':
        # 拒单,并填写拒单原因
        reason = req_data.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        order.status = 'REJECTED'
        order.comment = reason

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.seeion.rollback()
        return jsonify(errno=RET.DBERR, errmsg='操作失败')

    return jsonify(errno=RET.OK, errmsg="OK")


@order.route('/orders/comment', methods=['PUT'])
@login_required
def order_comment(order_id):
    """评价订单"""
    user_id = g.user_id

    # 获取参数
    req_data = request.get_json()
    comment = req_data.get('comment')

    # 校验参数
    if not comment:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 只能评论自己下的单,订单状态是待评价
    try:
        order = Order.query.filter(Order.id == order_id, Order.user_id == user_id,
                                   Order.status == 'WAIT_COMMENT').first()
        house = order.house
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.REQERR, errmsg='无法获取订单')

    if not order:
        return jsonify(errno=RET.REQERR, errmsg='操作无效')

    try:
        # 订单状态为已完成
        order.status = 'COMPLETE'
        # 保存订单评价信息
        order.comment = comment
        # 房屋完成订单数量+1
        house.order_count += 1

        db.session.add(order)
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()

        return jsonify(errno=RET.DBERR, errmsg='操作失败')
    # 因为房屋详情中有订单的评价信息,要让最新评价展示在房屋详情中,删除redis中关于本订单房屋的详情缓存
    try:
        redis_store.delete('house_info_%s' % order.house.id)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg="OK")
